package cn.itcast.oa.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.task.Task;
import org.springframework.stereotype.Service;

import cn.itcast.oa.base.BaseDAOimpl;
import cn.itcast.oa.model.Application;
import cn.itcast.oa.model.ApproveInfo;
import cn.itcast.oa.model.TaskView;
import cn.itcast.oa.model.User;
import cn.itcast.oa.service.ApplicationService;

@Service
public class ApplicationServiceImpl extends BaseDAOimpl<Application> implements ApplicationService {

	@Resource
	private ProcessEngine processEngine;
	
	//定义日期的显示格式为年月日
	private SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
	@Override
	public void submit(Application application) {
		// TODO Auto-generated method stub
		application.setApplyTime(new Date());
		application.setStatus(Application.STATUS_RUNNING);
		application.setTitle(application.getApplicationTemplate().getName()
				+"_"+application.getApplicant().getName()+
				"_"+sdf.format(application.getApplyTime()));
		getSession().save(application);
		
		// >> 准备流程变量
		Map<String, Object> variablesMap = new HashMap<String, Object>();
	    variablesMap.put("application", application);
	    
	    //得到申请模板的名称
	    String pdkey=application.getApplicationTemplate().getProcessDefinitionKey();
		ProcessInstance pi=processEngine.getExecutionService().startProcessInstanceByKey(pdkey,variablesMap);
		
		
		//在提交申请的时候也就是一个任务的完成
		Task task= processEngine.getTaskService()
				.createTaskQuery()
				.processInstanceId(pi.getId())
				.uniqueResult();
		processEngine.getTaskService().completeTask(task.getId());
	}
	
	/**
	 * 准备我的任务列表的数据
	 */
	@Override
	public List<TaskView> getMyTaskViewList(User currentUser) {
		// TODO Auto-generated method stub
		String userId=currentUser.getLoginName();//规定为用户的登录名称
		List<Task> taskList=processEngine.getTaskService().findPersonalTasks(userId);
		
		List<TaskView> resultList=new ArrayList<TaskView>();
		for(Task task:taskList){
			Application application = (Application) processEngine.getTaskService().getVariable(task.getId(), "application");
			resultList.add(new TaskView(task, application));
		}
		
		return resultList;
	}
	
	/**
	 * 审批信息的处理
	 */
	@Override
	public void approve(ApproveInfo approveInfo, String taskId,String outcome) {
		// TODO Auto-generated method stub
		getSession().save(approveInfo);
		
		Task task=processEngine.getTaskService().getTask(taskId);
//		System.out.println("-*--------------"+taskId+"------------");
		if(outcome==null){
			processEngine.getTaskService().completeTask(taskId);
		}else{
			processEngine.getTaskService().completeTask(taskId, outcome);
		}
		
		// >> 取出所属的流程实例，如果取出的为null，说明流程实例执行完成了，已经变成了历史记录
		ProcessInstance pi = processEngine.getExecutionService().findProcessInstanceById(task.getExecutionId());
		//System.out.println("___________________________________+"+task.getExecutionId());

		Application application = approveInfo.getApplication();
		if (!approveInfo.isApproval()) {
			// 如果本环节不同意，则流程实例直接结束，申请的状态为：未通过
			if (pi != null) { // 如果流程还未结束
				processEngine.getExecutionService().endProcessInstance(task.getExecutionId(), ProcessInstance.STATE_ENDED);
			}
			application.setStatus(Application.STATUS_REJECTED);
		} else {
			// 如果本环节同意，而且本环节是最后一个环节，则流程实例正常结束，申请的状态为：已通过
			if (pi == null) { // 本环节是最后一个环节，即流程已经结束了
				application.setStatus(Application.STATUS_APPROVED);
			}
		}
		getSession().update(application);
	}
	
	@Override
	public Set<String> getOutComesByTaskId(String taskId) {
		// 可以得到流程的分支路线的方法getOUtcomes（）
		return  processEngine.getTaskService().getOutcomes(taskId);
	}
}
